package com.misc;

import android.graphics.Bitmap;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class Tool {
	public static void sendByteArray(DataOutputStream dos, byte[] byteArray) throws IOException, InterruptedException {
		dos.writeInt(byteArray.length);
		
		int currentPosition = 0;
		int byteNumberToCopy = 0;
		while (currentPosition != byteArray.length) {
			byteNumberToCopy = (byteArray.length-currentPosition >= 512) ? 512 : byteArray.length-currentPosition;
			byte[] tempByteArray = new byte[byteNumberToCopy];
			System.arraycopy(byteArray, currentPosition, tempByteArray, 0, byteNumberToCopy);
			currentPosition += byteNumberToCopy;
			dos.write(tempByteArray, 0, byteNumberToCopy);
		}
		Thread.sleep(150);
	}

	
	public static byte[] receiveByteArray(DataInputStream dis) throws IOException, InterruptedException {
		byte[] byteArray = new byte[dis.readInt()];
		
		int currentPosition = 0;
		int byteNumberToCopy = 0;
		while (currentPosition != byteArray.length) {
			byteNumberToCopy = (byteArray.length-currentPosition >= 512) ? 512 : byteArray.length-currentPosition;
			byte[] tempByteArray = new byte[byteNumberToCopy];
			dis.read(tempByteArray, 0, byteNumberToCopy);
			System.arraycopy(tempByteArray, 0, byteArray, currentPosition, byteNumberToCopy);
			currentPosition += byteNumberToCopy;
		}
		Thread.sleep(150);
		
		return byteArray;
	}
	
	public static byte[] bitmap2ByteArray(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
}
